package com.hnas.eCard.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.eCard.dao.ECardShareCodeDao;
import com.hnas.eCard.orm.ECardShareCode;

@Component("eCardShareCodeDao")
public class ECardShareCodeDaoImpl extends BaseDaoImpl<ECardShareCode> implements ECardShareCodeDao{

	public ECardShareCodeDaoImpl() {
		super(ECardShareCode.class);
	}

	@Override
	public ECardShareCode saveOrUpdate(ECardShareCode vo) throws Exception {
		ECardShareCode temp = null;
		if(null != vo){
			if(StringUtil.isNotEmpty(vo.getId())){
				temp = this.find(vo.getId());
			}
			if(null == temp){
				temp = vo;
				temp.setCreateTime(DateUtil.dateTimeToString(new Date()));
				temp.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				temp.setIsDeleted(false);
				this.persist(temp);
			}else{
				BeanUtils.copyProperties(vo, temp,new String[]{"id", "createTime"});
				temp.setUpdateTime(DateUtil.dateTimeToString(new Date()));
				this.merge(temp);
			}
		}
		return temp;
	}

	@Override
	public ECardShareCode findByCardNo(String cardNo) throws Exception {
		String hql = "from ECardShareCode t where t.cardNo = ?1 and t.isDeleted=?2";
		List<ECardShareCode> list = this.findByQuery(hql,cardNo,false);
		if(list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public ECardShareCode findByShareCode(String shareCode) throws Exception {
		String hql = "from ECardShareCode t where t.shareCode = ?1 and t.isDeleted=?2";
		List<ECardShareCode> list = this.findByQuery(hql,shareCode,false);
		if(list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public void disableBefore(String cardNo) throws Exception {
		String sql = "update tbl_ecard_share_code set is_deleted=1 where is_deleted=0 and card_no = ?1";
		Query query = this.entityManager.createNativeQuery(sql);
		query.setParameter(1, cardNo);
		query.executeUpdate();
	}

}
